package org.mineground.player;

import java.sql.PreparedStatement;
import java.util.Date;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerJoinEvent;
import org.mineground.Main;
import org.mineground.Utilities;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @name PlayerJoinLogger.java
 * @author Daniel Koenen (2012)
 */
public class PlayerJoinLogger {
    private static final Logger ExceptionLogger = LoggerFactory.getLogger(PlayerJoinLogger.class);
    
    public static void addLog(PlayerJoinEvent joinEvent) {
        Player joinPlayer = joinEvent.getPlayer();
        
        String playerName = joinPlayer.getName();
        String ipAddressString = joinPlayer.getAddress().getAddress().getHostAddress();
        String countryCode = Main.getInstance().getGeoIPService().getCountry(ipAddressString).getCode();
        
        long joinTimestamp = (new Date().getTime() / 1000L);
        long ipAddress = Utilities.ipToLong(ipAddressString);
        
        try {
            PreparedStatement queryStatement = Main.getInstance().getDatabaseHandler().getConnection().prepareStatement("INSERT INTO lvm_player_joins (login_name, ip_address, join_date, country_code) VALUES (?, ?, FROM_UNIXTIME(?), ?)");
            queryStatement.setString(1, playerName);
            queryStatement.setLong(2, ipAddress);
            queryStatement.setLong(3, joinTimestamp);
            queryStatement.setString(4, ((countryCode.length() > 0) ? (countryCode) : ("--")));
            queryStatement.execute();
        }
        
        catch (Exception exception) {
            ExceptionLogger.error("Exception caught", exception);
        }
    }
}
